<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { saveOrUpdate } from './GrowthcyclePropertites.api';

const isUpdate = ref(true);
const rowId = ref('');

const emit = defineEmits(['success', 'register']);

const formSchema = [
  {
    field: 'id',
    label: 'ID',
    component: 'Input',
    show: false,
  },
  {
    field: 'growthcycleId',
    label: '生长周期ID',
    component: 'Input',
    show: false,
  },
  {
    field: 'code',
    label: '属性名称',
    component: 'JTreeSelect',
    componentProps: {
      dict: "t_classification,name,id",
      pidField: "pid",
      pidValue: "1861668518137614337",
      hasChildField: 'false'
    },
    required: true,
  },
  {
    field: 'unit',
    label: '单位',
    component: 'Input',
  },
  {
    field: 'value',
    label: '值',
    component: 'InputNumber',
    componentProps:{
      //带标签的 input，设置后置标签
      // addonBefore:'保留两位小数',
      //最大值
      // max:100,
      //数值精度
      // precision:2,
      //步数
      // step: 0.1
    },
    required: true,
  },
  {
    field: 'pic',
    label: '图片',
    component: 'JImageUpload',
    componentProps: {
      fileMax: 1,
    },
  },
];

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    rowId.value = data.record.id;
    setFieldsValue({
      ...data.record,
    });
  } else {
    // 新增
    setFieldsValue({
      growthcycleId: data.growthcycleId,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增生长周期属性' : '编辑生长周期属性'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    await saveOrUpdate(values, isUpdate.value);
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
